package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Device;
import com.example.service.DeviceService;
import com.example.mapper.DeviceMapper;
import com.example.util.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * @author luo20
 * @description 针对表【device(设备表)】的数据库操作Service实现
 * @createDate 2025-06-23 10:12:45
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device>
        implements DeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public int addDevice(Device device) {
        // 创建时间
        device.setCreateTime(LocalDateTime.now());
        // 更新时间
        device.setUpdateTime(LocalDateTime.now());
        return deviceMapper.insert(device);
    }

    @Override
    public PageResult<Device> pageDevices(HashMap<String, Object> hashMap) {
        // 类型
        Integer type = (Integer) hashMap.get("type");
        // 状态
        Integer status = (Integer) hashMap.get("status");
        // 开启分页
        PageHelper.startPage(1, 5);
        // 根据条件查询
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(type), Device::getType, type);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), Device::getStatus, status);

        List<Device> deviceList = deviceMapper.selectList(queryWrapper);
        //分页
        Page<Device> devicePage = (Page<Device>) deviceList;
        //返回数据
        return PageResult.<Device>builder().total(devicePage.getTotal()).rows(devicePage.getResult()).build();
    }

    @Override
    public Integer updateDeviceById(Integer deviceId, Integer status) {
        LambdaUpdateWrapper<Device> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Device::getId, deviceId);
        updateWrapper.set(Device::getStatus, status);
        return deviceMapper.update(updateWrapper);
    }
}




